import { modal } from 'vue-strap'
import DatePicker from 'vue-datepicker'
import getDatePickerOption from '../../../../util/date-picker-option'
import { showMsg, addCustom, updateCustom } from '../../../../vuex/action'

const validation = {
  custom(data) {
    let startTime = new Date(data.startTime).getTime()
    let endTime = new Date(data.endTime).getTime()
    if (!startTime) {
      return false
    }
    if (!endTime) {
      return false
    }
    if (startTime >= endTime) {
      return false
    }
    return true
  }
}

export default {
  name: 'custom-configure',
  components: {
    'vue-modal': modal,
    'vue-date-picker': DatePicker
  },
  props: ['title', 'custom', 'showCustom'],
  data() {
    return {
      datePickerOption: getDatePickerOption()
    }
  },
  vuex: {
    actions: {
      xShowMsg: showMsg,
      xAddCustom: addCustom,
      xUpdateCustom: updateCustom
    }
  },
  methods: {
    dipartiteRequest(data) {
      // 更改
      if (data.id) {
        this.xUpdateCustom(data)
          .then(() => {
            this.showCustom = false
          })
          .catch((res) => {
            this.xShowMsg({
              type: 'danger',
              content: res.error_msg
            })
          })
      } else {
        // 新增
        delete data.id
        this.xAddCustom(data)
          .then(() => {
            this.showCustom = false
          })
          .catch((res) => {
            this.xShowMsg({
              type: 'danger',
              content: res.error_msg
            })
          })
      }
    },
    submit() {
      let custom = this.custom
      // 验证信息
      let valid = validation.custom(custom)
      if (!valid) {
        return this.xShowMsg({
          type: 'danger',
          content: '请输入正确的时间'
        })
      }

      // 请求接口
      this.dipartiteRequest(custom)
    }
  }
}
